<?php

namespace Admin\Model\DAO;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

class OrderOnlineTable extends AbstractTableGateway {

    protected $table;
    protected $adapter;
    protected $resultSetPrototype;

    public function __construct(Adapter $adapter) {
        $this->table = 'lib_orderonline';
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
    }

    public function fetchAll() {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from(array('ol' => $this->table))
                ->join(array('sb' => 'lib_serialbooks'), 'sb.bookID = ol.bookID')
                ->join(array('bs' => 'lib_bookstores'), 'bs.bookBarcode = sb.bookBarcode');
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $resultSet = clone $this->resultSetPrototype;
        $resultSet->initialize($result);
        $resultSet->buffer();
        $resultSet->next();
        return $resultSet;
    }

    public function getBookID($bookID) {
        $rowset = $this->select(array('bookID' => $bookID));
        $row = $rowset->current();
        if (!$row)
            return null;
        else
            return $row;
    }

    public function getBookOrder($cardBarcode) {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from(array('ol' => $this->table))
                ->join(array('sb' => 'lib_serialbooks'), 'sb.bookID = ol.bookID')
                ->join(array('bs' => 'lib_bookstores'), 'bs.bookBarcode = sb.bookBarcode');
        $where = new Where();
        $where->equalTo('cardBarcode', $cardBarcode);
        $select->where($where);
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $resultSet = clone $this->resultSetPrototype;
        $resultSet->initialize($result);
        $resultSet->buffer();
        $resultSet->next();
        return $resultSet;
    }

    public function saveData($data) {
        $this->insert($data);
    }
    public function updateOrderStatus($bookID, $orderStatus) {
        $this->update(array('orderStatus' => $orderStatus), array('bookID' => $bookID));
    }
    public function deleteOrderBook($bookID) {
        $this->delete(array('bookID' => $bookID));
    }
}

?>
